package com.googlecode.wickedforms.xvergabe.pdf;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Reader;

import org.apache.wicket.util.io.IOUtils;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlOptions;
import org.xvergabe.forms.poc.helper.JavaScriptGenerator;
import org.xvergabe.forms.poc.pdfgenerator.FormPdfWriter;
import org.xvergabe.xsd.forms.components.x20.FormDocument;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.events.FieldPositioningEvents;

public class PdfExporter {

	/**
	 * Exportiert einen XVergabe-konformen XML-String in ein PDF-Formular, das
	 * in den angegebenen {@link OutputStream} geschrieben wird.
	 * 
	 * @param xml
	 *            der zu exportierende XML-String
	 * @param out
	 *            Outputstream, in den das PDF geschrieben wird.
	 */
	public void export(Reader xmlReader, OutputStream out) {

		FormPdfWriter formPdfWriter = new FormPdfWriter();
		Document doc = new Document();
		PdfWriter writer;
		FormDocument form;
		

		try {

			String xmlString = IOUtils.toString(xmlReader);
			form = FormDocument.Factory.parse(xmlString, new XmlOptions().setCharacterEncoding("UTF-8"));

			writer = PdfWriter.getInstance(doc, out);
			doc.open();

			writer.setPageEvent(new FieldPositioningEvents());

			formPdfWriter.writePdfFromXml(form.getForm(), writer, doc);
			System.out.println("done writing PDF");
			
			writer.addJavaScript(JavaScriptGenerator.getInstance().getInitialConfigs());
			System.out.println("done writing default value JavaScripts");
			
			writer.addJavaScript(JavaScriptGenerator.getInstance().getFunctions(form.getForm().getMetadata()));
			System.out.println("done writing JavaScript super- and subfunctions");	
			
			doc.close();
			writer.close();

		} catch (XmlException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
